import { Provide } from '@midwayjs/core';
import { ServicesImpl } from '../impl';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { TreeRepository } from 'typeorm';
import { ArticleCategory } from '../../model/article_category/article_category';
import { ArticleCategorySchema } from '../../schema';

@Provide()
export class ArticleCategoryService extends ServicesImpl {
  /**
   * 覆盖实体
   */
  @InjectEntityModel(ArticleCategory)
  services: TreeRepository<ArticleCategory>;

  /**
   * 重写关系
   */
  relations: Array<string>;

  constructor() {
    super();
    this.relations = ['parent'];
  }

  async trees() {
    return await this.services.findTrees({ relations: this.relations });
  }

  async save(params: ArticleCategorySchema) {
    const category = await this.services.findOne({
      where: { id: params.parent?.id },
    });
    Object.assign(params, { parent: category });
    return await this.services.save(params);
  }
}
